package com.chcit.mobile.mvp.inventory.fragment.move;

import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.chcit.mobile.app.base.ScanToolQueryFragment;
import com.google.android.material.textfield.TextInputEditText;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chcit.custom.view.loader.QuickLoader;
import com.chcit.custom.view.spinner.DropDownMenu;
import com.chcit.mobile.R;
import com.chcit.mobile.di.component.DaggerInventoryComponent;
import com.chcit.mobile.di.module.CommonModule;
import com.chcit.mobile.di.module.InventoryModule;
import com.chcit.mobile.helper.recycler.RecycleViewDivider;
import com.chcit.mobile.mvp.common.model.MenuTypeEnum;
import com.chcit.mobile.mvp.inventory.contract.InventoryContract;
import com.chcit.mobile.mvp.entity.BpartnerBean;
import com.chcit.mobile.mvp.entity.Statu;
import com.chcit.mobile.mvp.entity.InventoryBean;
import com.chcit.mobile.mvp.inventory.presenter.InventoryPresenter;
import com.chcit.mobile.mvp.common.adapter.GirdDropDownAdapter;
import com.chcit.mobile.mvp.inventory.adapter.InventoryAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.xuexiang.xui.widget.toast.XToast;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class InventoryFragment extends ScanToolQueryFragment<InventoryPresenter> implements InventoryContract.View {
    
    @BindView(R.id.pr_inventory_dropDownMenu)
    DropDownMenu mDropDownMenu;
    @BindView(R.id.lv_inventory_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.tv_inventory_describe)
    TextView tvDesc;
    protected MenuTypeEnum type ;
    private ArrayList<BpartnerBean> bpartners;
    private TextInputEditText tivetPackageNo;
    private TextInputEditText tietLocator;
    private BpartnerBean bpartnerBean;
    private Statu mStatu;
    private String headers[] = {"选择货主", "输入商品", "存货状态"};
    private InventoryBean storageBean;
    private List<InventoryBean> storageBeans = new ArrayList<>();
    protected InventoryAdapter mAdapter = new InventoryAdapter(storageBeans);
    private int REQUEST_CODE = this.getClass().hashCode();

    public static InventoryFragment newInstance() {
        InventoryFragment fragment = new InventoryFragment();
        return fragment;
    }


    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerInventoryComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .inventoryModule(new InventoryModule(this,mAdapter))
                .commonModule(new CommonModule())
                .build()
                .inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_inventory;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
//        if (type == null) {
//            mCommonToolbar.setTitleText("库存查询");
//        } else {
//            mCommonToolbar.setTitleText("移库");
//        }
        this.mAdapter.setType(this.type);
        mCommonToolbar.getLeftMenuView(0).setOnClickListener(l -> {
            pop();
            l.setOnClickListener(null);
            if (getActivity() != null) {
                _mActivity.finish();
            }

        });
        vetPackageNo.setHint("请扫描货位码");
        initDropDownMenu();
    }

   
    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
        QuickLoader.showLoading(mContext);
    }

    @Override
    public void hideLoading() {
        QuickLoader.stopLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        XToast.info(mContext,message).show();
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        pop();
        getActivity().finish();
    }

    private void initDropDownMenu() {
        final List<View> popupViews = new ArrayList<>();

        //供应商选择
        final ListView wareView = new ListView(getContext());
        bpartners = new ArrayList<>();
        bpartners.add(new BpartnerBean(1,"不限"));

        final GirdDropDownAdapter<BpartnerBean> bpartnerAdapter = new GirdDropDownAdapter<BpartnerBean>(getContext(), bpartners);
        wareView.setDividerHeight(0);
        wareView.setAdapter(bpartnerAdapter);
        wareView.setOnItemClickListener((parent, view, position, id) -> {
            bpartnerAdapter.setCheckItem(position);
            bpartnerBean = bpartners.get(position);
            if (position == 0) {
                bpartnerBean = null;
            }
            mDropDownMenu.setTabText(position == 0 ? headers[0] : bpartnerBean.getName());
            mDropDownMenu.closeMenu();
        });

        //商品选择
        final View constellationView = getLayoutInflater().inflate(R.layout.pop_inventory, null);
        tivetPackageNo = constellationView.findViewById(R.id.constellation);//厂家
        tietLocator = constellationView.findViewById(R.id.pop_inventory_locator);
        constellationView.findViewById(R.id.reset).setOnClickListener(v->{
            tivetPackageNo.setText("");
            tietLocator.setText("");
        });
        Button ok = constellationView.findViewById(R.id.ok);
        ok.setOnClickListener(v -> {
            String text = tivetPackageNo.getText().toString();
            mDropDownMenu.setTabText(text.isEmpty() ? headers[1] : text);
            mDropDownMenu.closeMenu();
        });

        //存货状态
        final ListView dateView = new ListView(getContext());

        final List<Statu> status = new ArrayList<>();
        status.add(new Statu("", "不限"));
        final GirdDropDownAdapter<Statu> dateAdapter = new GirdDropDownAdapter<Statu>(getContext(), status);
        dateView.setDividerHeight(0);
        dateView.setAdapter(dateAdapter);
        dateView.setOnItemClickListener((parent, view, position, id) -> {
            dateAdapter.setCheckItem(position);
            mStatu = status.get(position);
            if (position == 0) {
                mStatu = null;
            }
            mDropDownMenu.setTabText(position == 0 ? headers[2] : status.get(position).getName());
            mDropDownMenu.closeMenu();
        });
        popupViews.add(wareView);
        popupViews.add(constellationView);
        popupViews.add(dateView);
        final TextView contentView = new TextView(getContext());
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        contentView.setText("");
        //contentView.setBackgroundColor(getResources().getColor(R.color.gray));
        contentView.setGravity(Gravity.CENTER);
        contentView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
        final List<String> list = Arrays.asList(headers);
        mDropDownMenu.setDropDownMenu(list, popupViews, contentView);

        mPresenter.getBpartners(bpartnerBeans -> {
            bpartners.addAll(bpartnerBeans);
            bpartnerAdapter.notifyDataSetChanged();
        });


        mPresenter.getStatus(status1 -> {
            status.addAll(status1);
            dateAdapter.notifyDataSetChanged();
        });

    }

    private int itemPosition = -1;

    private void initRecyclerView() {

        //ArmsUtils.configRecyclerView(mRecyclerView, mLayoutManager);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.addItemDecoration(new RecycleViewDivider(getContext(), LinearLayoutManager.HORIZONTAL, R.drawable.item_drivide_style));
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mAdapter.loadMoreComplete();
                getData();
            }
        }, mRecyclerView);
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            if(position >=0 && adapter.getData().size()>position){
                itemPosition = position;
                mAdapter.setCheckedPosition(position);
                storageBean = (InventoryBean) adapter.getData().get(position);
                startForResult(InventoryDetailFragment.newInstance(storageBean, type), REQUEST_CODE);
            }

        });
        mRecyclerView.setAdapter(mAdapter);

    }
    private void getData() {
        JSONObject data = new JSONObject();
               /* start:0
                limit:25
                bpartnerID:1019706
                showLot:true
                appSessionID:1541585528858.6*/

        if (!vetPackageNo.getText().toString().isEmpty()) {
            data.put("locatorValue", vetPackageNo.getText().toString());
        }
        if (!tivetPackageNo.getText().toString().isEmpty()) {
            data.put("productName", tivetPackageNo.getText().toString());
        }
        if (!tietLocator.getText().toString().isEmpty()) {
            data.put("manufacturer", tietLocator.getText().toString());
        }
        if (mStatu != null) {
            data.put("storageStatus", mStatu.getId());
        }
        if (bpartnerBean != null) {
            data.put("bpartnerBean", bpartnerBean.getId());
        }
        mPresenter.getData(data, list -> {
            mAdapter.addData(list);

        });
    }
    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {
        vetPackageNo.setText(barcodeData);
        btQuery.performClick();
    }

    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        initRecyclerView();

    }

    @OnClick({R.id.bt_common_query})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_common_query:
                mAdapter.getData().clear();
                mAdapter.notifyDataSetChanged();
                mPresenter.setmStart(0);
                showLoading();
                getData();
                break;
        }
    }


    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            if(itemPosition >=0&& mAdapter.getData().size()>0){
                if(vetPackageNo.getText().toString().isEmpty()){
                    vetPackageNo.setText(storageBeans.get(itemPosition).getLocatorName());
                }
                mPresenter.setmStart(0);
                getData();
            }

        }
    }


    @Override
    public void showDataTotal(String total) {
        tvDesc.setText("总共"+total+"条数据");
    }
}
